package com.lych.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lych.commons.utils.Constants;
import com.lych.dubbo.api.CommentApi;
import com.lych.dubbo.api.UserInfoApi;
import com.lych.model.domain.UserInfo;
import com.lych.model.enums.CommentType;
import com.lych.model.mongo.Comment;
import com.lych.model.vo.CommentVo;
import com.lych.model.vo.ErrorResult;
import com.lych.model.vo.PageResult;
import com.lych.server.exception.BusinessException;
import com.lych.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.builder.BuilderException;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 评论-提交
     * @param map
     */
    public void saveComments(Map map) {
        String movementId = (String) map.get("movementId"); //动态编号
        String comment = (String) map.get("comment");       //评论
        //得到当前评论人id
        Long userId = UserHolder.getUserId();
        //构造Comment
        Comment comment1 = new Comment();
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setCreated(System.currentTimeMillis());
        comment1.setUserId(userId);
        comment1.setPublishId(new ObjectId(movementId));
        //调用你api保存评论
        Integer integer = commentApi.saveComments(comment1);
        log.info("commentCount = " + integer);
        //发送消息日志
        mqMessageService.sendLogService(userId,"0205","movement",movementId);
    }

    /**
     * 分页查询评论列表
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //调用api分页查询评论列表
        List<Comment> list = commentApi.findComments(movementId,CommentType.COMMENT,page,pagesize);
        //非空判断
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //在list中拿到用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(userIds, null);
        //构造返回对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = infoMap.get(comment.getUserId());
            if(userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    /**
     * 评论点赞
     * @param commentId
     * @return
     */
    public Integer idLike(String commentId) {
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        //调用redis查看是否已经点赞
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(key,hashKey);
        //如果已经点赞，抛异常
        if (aBoolean) {
            throw new BusinessException(ErrorResult.likeError());
        }
        Comment comment = new Comment();
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setId(new ObjectId(commentId));
        Integer integer = commentApi.saveComment(comment);
        //拼接key，将用户点赞信息存入redis

        redisTemplate.opsForHash().put(key,hashKey,"1");
        return integer;
    }

    /**
     * 取消评论点赞
     * @param commentId
     * @return
     */
    public Integer idDisLike(String commentId) {
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        //调用redis查看是否已经点赞
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(key,hashKey);
        //如果没有点赞，抛异常
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        Comment comment = new Comment();
        comment.setId(new ObjectId(commentId));
        comment.setCommentType(CommentType.LIKE.getType());
        Integer integer = commentApi.deleteCommentId(comment);
        redisTemplate.opsForHash().delete(key,hashKey);
        return integer;
    }
}
